<template>
  <div>
    <topBar/>
    <main class="profile-page">
      <section class="relative block h-500-px">
        <div
            class="absolute top-0 w-full h-full bg-center bg-cover"
            :style="{'backgroundImage':`url(${background1}`}"
        >
        </div>
        <div
            class="top-auto bottom-0 left-0 right-0 w-full absolute pointer-events-none overflow-hidden h-70-px"
            style="transform: translateZ(0);"
        >
          <svg
              class="absolute bottom-0 overflow-hidden"
              xmlns="http://www.w3.org/2000/svg"
              preserveAspectRatio="none"
              version="1.1"
              viewBox="0 0 2560 100"
              x="0"
              y="0"
          >
            <polygon
                class="text-blueGray-200 fill-current"
                points="2560 0 2560 100 0 100"
            ></polygon>
          </svg>
        </div>
      </section>
      <section class="relative py-16 bg-blueGray-200">
        <div class="container mx-auto px-4">
          <div
              class="relative flex flex-col min-w-0 break-words bg-white w-full mb-6 shadow-xl rounded-lg -mt-64"
          >
            <div class="px-6">
              <div class="flex flex-wrap justify-center">
                <div
                    class="w-full lg:w-3/12 px-4 lg:order-2 flex justify-center"
                >
                  <div class="relative">
                    <img
                        alt="..."
                        :src="userInfo.header"
                        class="shadow-xl rounded-full h-auto align-middle border-none absolute -m-16 -ml-20 lg:-ml-16 max-w-150-px"
                    />
                  </div>
                </div>

                <!--展示收货地址-->
                <a-modal width="990px" v-model:open="addressVisible" title="收货地址">
                  <template #footer>
                  </template>
                  <a-button class="editable-add-btn" style="margin-bottom: 8px" @click="handleAdd">添加</a-button>
                  <a-table bordered :data-source="dataSource" :columns="columns">
                    <template #bodyCell="{ column, text, record }">
                      <template v-if="column.dataIndex === 'name'">
                        <div class="editable-cell">
                          <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
                            <a-input v-model:value="editableData[record.key].name" @pressEnter="save(record.key)" />
                            <check-outlined class="editable-cell-icon-check" @click="save(record.key)" />
                          </div>
                          <div v-else class="editable-cell-text-wrapper">
                            {{ text || ' ' }}
                            <edit-outlined class="editable-cell-icon" @click="edit(record.key)" />
                          </div>
                        </div>
                      </template>
                      <template v-if="column.dataIndex === 'phone'">
                        <div class="editable-cell">
                          <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
                            <a-input v-model:value="editableData[record.key].phone" @pressEnter="save(record.key)" />
                            <check-outlined class="editable-cell-icon-check" @click="save(record.key)" />
                          </div>
                          <div v-else class="editable-cell-text-wrapper">
                            {{ text || ' ' }}
                            <edit-outlined class="editable-cell-icon" @click="edit(record.key)" />
                          </div>
                        </div>
                      </template>
                      <template v-if="column.dataIndex === 'province'">
                        <div class="editable-cell">
                          <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
                            <a-input v-model:value="editableData[record.key].province" @pressEnter="save(record.key)" />
                            <check-outlined class="editable-cell-icon-check" @click="save(record.key)" />
                          </div>
                          <div v-else class="editable-cell-text-wrapper">
                            {{ text || ' ' }}
                            <edit-outlined class="editable-cell-icon" @click="edit(record.key)" />
                          </div>
                        </div>
                      </template>
                      <template v-if="column.dataIndex === 'city'">
                        <div class="editable-cell">
                          <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
                            <a-input v-model:value="editableData[record.key].city" @pressEnter="save(record.key)" />
                            <check-outlined class="editable-cell-icon-check" @click="save(record.key)" />
                          </div>
                          <div v-else class="editable-cell-text-wrapper">
                            {{ text || ' ' }}
                            <edit-outlined class="editable-cell-icon" @click="edit(record.key)" />
                          </div>
                        </div>
                      </template>
                      <template v-if="column.dataIndex === 'region'">
                        <div class="editable-cell">
                          <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
                            <a-input v-model:value="editableData[record.key].region" @pressEnter="save(record.key)" />
                            <check-outlined class="editable-cell-icon-check" @click="save(record.key)" />
                          </div>
                          <div v-else class="editable-cell-text-wrapper">
                            {{ text || ' ' }}
                            <edit-outlined class="editable-cell-icon" @click="edit(record.key)" />
                          </div>
                        </div>
                      </template>
                      <template v-if="column.dataIndex === 'detailAddress'">
                        <div class="editable-cell">
                          <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
                            <a-input v-model:value="editableData[record.key].detailAddress" @pressEnter="save(record.key)" />
                            <check-outlined class="editable-cell-icon-check" @click="save(record.key)" />
                          </div>
                          <div v-else class="editable-cell-text-wrapper">
                            {{ text || ' ' }}
                            <edit-outlined class="editable-cell-icon" @click="edit(record.key)" />
                          </div>
                        </div>
                      </template>
                      <template v-if="column.dataIndex === 'defaultStatus'">
                        <a-checkbox @change="changeDefaultStatus(record.key)" v-model:checked="record.defaultStatus"/>
                      </template>
                      <template v-else-if="column.dataIndex === 'operation'">
                        <a-popconfirm
                            v-if="dataSource.length"
                            title="确定删除?"
                            @confirm="onDelete(record.key)"
                        >
                          <a>删除</a>
                        </a-popconfirm>
                      </template>
                    </template>
                  </a-table>

                </a-modal>
                <!--添加收货地址视图-->
                <a-modal v-model:open="addReceiveAddressVisible" title="添加收货地址">
                  <template #footer>
                  </template>
                  <p style="text-align: left">
                    <a-form
                        :model="addressFormState"
                        v-bind="layout"
                        name="nest-messages"
                        :validate-messages="validateMessages"
                        @finish="onFinish"
                    >
                      <a-form-item name="name" label="收货人" :rules="[{ required: true }]">
                        <a-input v-model:value="addressFormState.name" />
                      </a-form-item>
                      <a-form-item name="phone" label="电话" :rules="[{ required: true }]">
                        <a-input v-model:value="addressFormState.phone" />
                      </a-form-item>
                      <a-form-item name="province" label="省">
                        <a-input v-model:value="addressFormState.province" />
                      </a-form-item>
                      <a-form-item name="city" label="市" :rules="[{ required: true }]">
                        <a-input v-model:value="addressFormState.city" />
                      </a-form-item>
                      <a-form-item name="region" label="区/县" :rules="[{ required: true }]">
                        <a-input v-model:value="addressFormState.region" />
                      </a-form-item>
                      <a-form-item name="detailAddress" label="详细地址" :rules="[{ required: true }]">
                        <a-textarea v-model:value="addressFormState.detailAddress" />
                      </a-form-item>
                      <a-form-item :wrapper-col="{ ...layout.wrapperCol, offset: 8 }">
                        <a-button :loading="addAddressloading" type="primary" html-type="submit">Submit</a-button>
                      </a-form-item>
                    </a-form>
                  </p>
                </a-modal>

                <div
                    class="w-full lg:w-4/12 px-4 lg:order-3 lg:text-right lg:self-center"
                >
                  <div class="py-6 px-3 mt-32 sm:mt-0">
                    <button
                        class="bg-emerald-500 active:bg-emerald-600 uppercase text-white font-bold hover:shadow-md shadow text-xs px-4 py-2 rounded outline-none focus:outline-none sm:mr-2 mb-1 ease-linear transition-all duration-150"
                        type="button"
                        @click = "getReceiveAddress"
                    >
                      收货地址
                    </button>
                  </div>
                </div>
                <div class="w-full lg:w-4/12 px-4 lg:order-1">
                  <div class="flex justify-center py-4 lg:pt-4 pt-8">
                    <div class="mr-4 p-3 text-center">
                      <span
                          class="text-xl font-bold block uppercase tracking-wide text-blueGray-600"
                      >
                        22
                      </span>
                      <span class="text-sm text-blueGray-400">Friends</span>
                    </div>
                    <div class="mr-4 p-3 text-center">
                      <span
                          class="text-xl font-bold block uppercase tracking-wide text-blueGray-600"
                      >
                        10
                      </span>
                      <span class="text-sm text-blueGray-400">Photos</span>
                    </div>
                    <div class="lg:mr-4 p-3 text-center">
                      <span
                          class="text-xl font-bold block uppercase tracking-wide text-blueGray-600"
                      >
                        89
                      </span>
                      <span class="text-sm text-blueGray-400">Comments</span>
                    </div>
                  </div>
                </div>
              </div>
              <div class="text-center mt-12">
                <h3
                    class="text-4xl font-semibold leading-normal mb-2 text-blueGray-700 mb-2"
                >
                  {{userInfo.nickname}}
                </h3>
                <div
                    class="text-sm leading-normal mt-0 mb-2 text-blueGray-400 font-bold uppercase"
                >
                  <i
                      class="fas fa-map-marker-alt mr-2 text-lg text-blueGray-400"
                  ></i>
                  {{userInfo.city}}
                </div>
                <div class="mb-2 text-blueGray-600 mt-10">
                  <i
                      class="fas fa-briefcase mr-2 text-lg text-blueGray-400"
                  ></i>
                  Solution Manager - Creative Tim Officer
                </div>
                <div class="mb-2 text-blueGray-600">
                  <i
                      class="fas fa-university mr-2 text-lg text-blueGray-400"
                  ></i>
                  University of Computer Science
                </div>
              </div>
              <div class="mt-10 py-10 border-t border-blueGray-200 text-center">
                <div class="flex flex-wrap justify-center">
                  <div class="w-full lg:w-9/12 px-4">
                    <p class="mb-4 text-lg leading-relaxed text-blueGray-700">
                      An artist of considerable range, Jenna the name taken by
                      Melbourne-raised, Brooklyn-based Nick Murphy writes,
                      performs and records all of his own music, giving it a
                      warm, intimate feel with a solid groove structure. An
                      artist of considerable range.
                    </p>
                    <a
                        href="javascript:void(0)"
                        class="font-normal text-emerald-500"
                    >
                      Show more
                    </a>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>

  </div>
</template>

<script setup>
import topBar from '@//components/common/TopBar.vue'
import background1 from '@/assets/img/background1.png'
import {computed, reactive, ref, onBeforeMount} from 'vue'
import request from "@/utils/request";
import {message} from "ant-design-vue";
import { cloneDeep } from 'lodash-es';
import { CheckOutlined, EditOutlined } from '@ant-design/icons-vue';

let userInfo = ref({})
let addressVisible = ref(false)
let addReceiveAddressVisible = ref(false)
let addAddressloading = ref(false)

//收货地址数据源
let dataSource = ref([])
let idIndexMap = new Map() //{key: addressId, value: dataSource.index}

const columns = [
  {
    title: '收件人',
    dataIndex: 'name',
  },
  {
    title: '电话',
    dataIndex: 'phone',
  },
  {
    title: "省",
    dataIndex: "province",
  },
  {
    title: '城市',
    dataIndex: "city"
  },
  {
    title: "区/县",
    dataIndex: "region"
  },
  {
    title: "详细地址",
    dataIndex: "detailAddress",
  },
  {
    title: "默认地址",
    dataIndex: "defaultStatus"
  }
  ,
  {
    title: '操作',
    dataIndex: 'operation',
  }
];

const addressFormState = reactive({
  name: '',
  phone: '',
  province: '',
  city: '',
  region: '',
  detailAddress: ''
})

const layout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};

const getUserInfo = ()=> {
  request({
    url: '/auth/user/get-userInfo',
    method: 'get'
  }).then(res => {
    if(res.code === 0){
      console.log(res)
      userInfo.value = res.data
      dataSource.value = res.data.receiveAddresses
      let index = 0
      dataSource.value.forEach(address => {
        address['key'] = address.id;
        address.defaultStatus = address.defaultStatus === 1
        idIndexMap.set(address.id, index)
        index++
      })
    }else {
      console.log('服务端获取session异常', res.msg)
      message.error(res.msg)
    }
  }).catch(err => {
    console.log('获取session异常', err.message)
  })
}

onBeforeMount(_=>{
  getUserInfo()
})

const count = computed(() => dataSource.value.length + 1);
const editableData = reactive({});

const getReceiveAddress = ()=>{
  addressVisible.value = true
}

const handleAdd = () => {
  addReceiveAddressVisible.value = true
}

// 确认添加收货地址逻辑
const onFinish = values => {
  console.log('提交的数据:', values);
  addAddressloading.value = true
  request({
    url: '/auth/user/add-address',
    method: 'post',
    data: request.adornData(values, false)
  }).then(res => {
    if(res.code === 0){
      message.success(res.msg)
      getUserInfo()
      addReceiveAddressVisible.value = false

      addressFormState.phone = ''
      addressFormState.region = ''
      addressFormState.name = ''
      addressFormState.city = ''
      addressFormState.detailAddress = ''
      addressFormState.province = ''
    } else {
      message.info(res.msg)
    }
  }).catch(err => {
    console.log(err.message)
    message.error(err.message)
  }).finally(_=>{
    addAddressloading.value = false
  })
};

const edit = key => {
  editableData[key] = cloneDeep(dataSource.value.filter(item => key === item.key)[0]);
};
const save = key => {
  //提交给后端更新的数据
  let postData = editableData[key]
  postData.defaultStatus = postData.defaultStatus? 1: 0
  request({
    url : '/auth/user/updateInfo',
    method: 'post',
    data: request.adornData({receiveAddresses: [postData]},false)
  }).then(res => {
    if(res.code === 0){
      editableData[key].defaultStatus = !!editableData[key].defaultStatus
      Object.assign(dataSource.value.filter(item => key === item.key)[0], editableData[key]);
      delete editableData[key];
      message.success(res.msg)
    } else {
      message.error(res.msg)
      console.log('更新收货地址异常-', res.msg)
    }
  }).catch(err => {
    console.log('更新收货地址异常-', err.message)
    message.error('更新收货地址异常-'+err.message)
  })
};
const onDelete = key => {
  request({
    url : '/auth/user/delAddress',
    method: 'post',
    data: request.adornData([key],false)
  }).then(res => {
    if(res.code === 0){
      message.success(res.msg)
      dataSource.value = dataSource.value.filter(item => item.key !== key);
    } else {
      message.error(res.msg)
      console.log('删除收货地址异常-', res.msg)
    }
  }).catch(err => {
    console.log('删除收货地址异常-', err.message)
    message.error('删除收货地址异常-'+err.message)
  })
};

/**
 *
 * @param addresses 地址数组
 */
const updateAddress = (addresses)=>{
  request({
    url : '/auth/user/updateInfo',
    method: 'post',
    data: request.adornData({receiveAddresses: addresses},false)
  }).then(res => {
    if(res.code === 0){
      message.success(res.msg)
    } else {
      message.error(res.msg)
      console.log('更新收货地址异常-', res.msg)
    }
  }).catch(err => {
    console.log('更新收货地址异常-', err.message)
    message.error('更新收货地址异常-'+err.message)
  })
}

function changeDefaultStatus(id){
  let address = dataSource.value[idIndexMap.get(id)]
  let postData
  if(address.defaultStatus === true){
    //清理掉其他的默认勾选
    for (let i = 0; i < dataSource.value.length; i++) {
      if(dataSource.value[i].defaultStatus === true && dataSource.value[i].id !== id){
        dataSource.value[i].defaultStatus = false
        postData = {...dataSource.value[i]}
        postData.defaultStatus = 0
        updateAddress([postData])
      }
    }
    //将勾选的设置为true
    dataSource.value[idIndexMap.get(id)].defaultStatus = true
    postData = {...dataSource.value[idIndexMap.get(id)]}
    postData.defaultStatus = 1
  } else {
    console.log('去掉默认')
    dataSource.value[idIndexMap.get(id)].defaultStatus = false
    postData = {...dataSource.value[idIndexMap.get(id)]}
    postData.defaultStatus = 0
  }
  updateAddress([postData])
}

const validateMessages = {
  required: '${label} is required!',
  types: {
    email: '${label} is not a valid email!',
    number: '${label} is not a valid number!',
  },
  number: {
    range: '${label} must be between ${min} and ${max}',
  },
};

// const imageUrl = new URL('../src/assets/img/background1.png', import.meta.url).href
</script>

<style scoped>
.editable-cell {
  position: relative;
  .editable-cell-input-wrapper,
  .editable-cell-text-wrapper {
    padding-right: 24px;
  }

  .editable-cell-text-wrapper {
    padding: 5px 24px 5px 5px;
  }

  .editable-cell-icon,
  .editable-cell-icon-check {
    position: absolute;
    right: 0;
    width: 20px;
    cursor: pointer;
  }

  .editable-cell-icon {
    margin-top: 4px;
    display: none;
  }

  .editable-cell-icon-check {
    line-height: 28px;
  }

  .editable-cell-icon:hover,
  .editable-cell-icon-check:hover {
    color: #108ee9;
  }

  .editable-add-btn {
    margin-bottom: 8px;
  }
}
.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}
</style>

